import React, { Component, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Row,
  Col,
  Icon,
  Card,
  Tabs,
  Table,
  Radio,
  DatePicker,
  Tooltip,
  Spin,
} from 'antd';
import numeral from 'numeral';
import {
  ChartCard,
  MiniBar,
  MiniProgress,
  Field,
  Bar,
  Pie,
} from 'components/Charts';
import Trend from 'components/Trend';
import { getTimeDistance } from '../../utils/utils';

import styles from './Statistics.less';

const { TabPane } = Tabs;
const { RangePicker } = DatePicker;


@connect(({ statistics, loading }) => ({
  statistics,
  loading: loading.effects.statistics,
}))
export default class Analysis extends Component {
  state = {
    hotType: '实时热点',
    rangePickerValue: getTimeDistance('year'),
  };


  componentDidMount() {
    const { dispatch } = this.props;
    const { rangePickerValue, hotType } = this.state;
    dispatch({
      type: 'statistics/fetchCount',
    });
    dispatch({
      type: 'statistics/fetchGroup',
    });
    dispatch({
      type: 'statistics/fetchRank',
      payload: {
        startDate: moment(rangePickerValue[0]).format('YYYY-MM-DD'),
        endDate: moment(rangePickerValue[1]).format('YYYY-MM-DD'),
      },
    });
    dispatch({
      type: 'statistics/fetchHot',
      payload: {
        type: hotType,
      },
    });
    dispatch({
      type: 'statistics/fetchRatio',
    });
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'statistics/clear',
    });
  }

  handleChangeHot = e => {
    this.setState({
      hotType: e.target.value,
    });
    const { dispatch } = this.props;
    dispatch({
      type: 'statistics/fetchHot',
      payload: {
        type: e.target.value,
      },
    });
  };

  handleRangePickerChange = rangePickerValue => {
    this.setState({
      rangePickerValue,
    });
    const { dispatch } = this.props;
    dispatch({
      type: 'statistics/fetchRank',
      payload: {
        startDate: moment(rangePickerValue[0]).format('YYYY-MM-DD'),
        endDate: moment(rangePickerValue[1]).format('YYYY-MM-DD'),
      },
    });
  };

  selectDate = type => {
    const pickerValue = getTimeDistance(type);
    this.setState({
      rangePickerValue: pickerValue,
    });
    let endDate = moment(pickerValue[1]).format('YYYY-MM-DD');
    if(type === 'today'){
      endDate = moment(pickerValue[1]).add(1, 'days').format('YYYY-MM-DD');
    }
    const { dispatch } = this.props;
    dispatch({
      type: 'statistics/fetchRank',
      payload: {
        startDate: moment(pickerValue[0]).format('YYYY-MM-DD'),
        endDate,
      },
    });
  };

  isActive(type) {
    const { rangePickerValue } = this.state;
    const value = getTimeDistance(type);
    if (!rangePickerValue[0] || !rangePickerValue[1]) {
      return;
    }
    if (
      rangePickerValue[0].isSame(value[0], 'day') &&
      rangePickerValue[1].isSame(value[1], 'day')
    ) {
      return styles.currentDate;
    }
  }

  render() {
    const { rangePickerValue, hotType } = this.state;
    const { statistics, loading } = this.props;
    const {
      articleCountData,
      baiJiaCountData,
      searchCountData,
      topicCountData,
      articleGroupData,
      baiJiaGroupData,
      articleRankData,
      baiJiaRankData,
      hotData,
      ratioData,
      ratioTotal,
    } =  statistics;

    const salesExtra = (
      <div className={styles.salesExtraWrap}>
        <div className={styles.salesExtra}>
          <a className={this.isActive('today')} onClick={() => this.selectDate('today')}>
            今日
          </a>
          <a className={this.isActive('week')} onClick={() => this.selectDate('week')}>
            本周
          </a>
        </div>
        <RangePicker
          value={rangePickerValue}
          onChange={this.handleRangePickerChange}
          style={{ width: 256 }}
        />
      </div>
    );

    const columns = [
      {
        title: '排名',
        dataIndex: 'rank',
        key: 'rank',
      },
      {
        title: '关键词',
        dataIndex: 'title',
        render: (text, record) => {
         return <a href={record.title_src} target="_bank">{record.title}</a>
        },
      },
      {
        title: '点击热度',
        dataIndex: 'search_count',
        align: 'right',
      },
    ];

    const topColResponsiveProps = {
      xs: 24,
      sm: 12,
      md: 12,
      lg: 12,
      xl: 6,
      style: { marginBottom: 24 },
    };

    return (
      <Spin tip="拼命加载中..." spinning={false}>
        <Fragment>
          <Row gutter={24}>
            <Col {...topColResponsiveProps}>
              <ChartCard
                bordered={false}
                title="百家文章"
                loading={loading}
                action={
                  <Tooltip title="文章总数">
                    <Icon type="info-circle-o" />
                  </Tooltip>
                }
                total={articleCountData.total === 0 ? "加载中.." : numeral(articleCountData.total).format('0,0')}
                footer={
                  <div>
                    <span>最高阅读: {numeral(articleCountData.maxViewEntity.view).format('0,0')}</span>
                    <span style={{ float:'right' }}><a href={articleCountData.maxViewEntity.src} target="_bank"> 去看看 </a></span>
                  </div>
                }
                contentHeight={46}
              >
                <Trend flag={articleCountData.trend} style={{ marginRight: 16 }}>
                  今日已入库
                  <span className={styles.trendText}>{numeral(articleCountData.current).format('0,0')}</span>
                </Trend>
                <Trend flag={articleCountData.trend}>
                  日环比
                  <span className={styles.trendText}>{articleCountData.ratio}%</span>
                </Trend>
              </ChartCard>
            </Col>
            <Col {...topColResponsiveProps}>
              <ChartCard
                bordered={false}
                title="百家仓库"
                loading={loading}
                action={
                  <Tooltip title="百家号总数">
                    <Icon type="info-circle-o" />
                  </Tooltip>
                }
                total={baiJiaCountData.total === 0 ? "加载中.." : numeral(baiJiaCountData.total).format('0,0')}
                footer={
                  <div>
                    <span>最多粉丝: {numeral(baiJiaCountData.maxFansEntity.fans).format('0,0')}</span>
                    <span style={{ float:'right' }}><a href={baiJiaCountData.maxFansEntity.home_url} target="_bank"> 去看看 </a></span>
                  </div>
                }
                contentHeight={46}
              >
                <Trend flag={baiJiaCountData.trend} style={{ marginRight: 16 }}>
                  今日已入库
                  <span className={styles.trendText}>{numeral(baiJiaCountData.current).format('0,0')}</span>
                </Trend>
                <Trend flag={baiJiaCountData.trend}>
                  日环比
                  <span className={styles.trendText}>{baiJiaCountData.ratio}%</span>
                </Trend>
              </ChartCard>
            </Col>
            <Col {...topColResponsiveProps}>
              <ChartCard
                bordered={false}
                title="热点话题"
                loading={loading}
                action={
                  <Tooltip title="热点话题总数">
                    <Icon type="info-circle-o" />
                  </Tooltip>
                }
                total={topicCountData.total === 0 ? "加载中.." : numeral(topicCountData.total).format('0,0')}
                footer={
                  <span>最新话题: <a href={topicCountData.maxNewEntity.title_src} target="_bank">{topicCountData.maxNewEntity.title}</a></span>
                }
                contentHeight={46}
              >
                <MiniProgress percent={78} strokeWidth={8} target={80} color="#13C2C2" />
              </ChartCard>
            </Col>
            <Col {...topColResponsiveProps}>
              <ChartCard
                bordered={false}
                title="热点点击"
                loading={loading}
                action={
                  <Tooltip title="热点话题的总点击数">
                    <Icon type="info-circle-o" />
                  </Tooltip>
                }
                total={searchCountData.total === 0 ? "加载中.." : numeral(searchCountData.total).format('0,0')}
                footer={<Field label="最多点击: " value={numeral(searchCountData.maxSearchEntity.search_count).format('0,0')} />}
                contentHeight={46}
              >
                <MiniBar data={searchCountData.countList} />
              </ChartCard>
            </Col>
          </Row>
          <Card loading={loading} bordered={false} bodyStyle={{ padding: 0 }}>
            <div className={styles.salesCard}>
              <Tabs tabBarExtraContent={salesExtra} size="large" tabBarStyle={{ marginBottom: 24 }}>
                <TabPane tab="文章采集" key="sales">
                  <Row>
                    <Col xl={16} lg={12} md={12} sm={24} xs={24}>
                      <div className={styles.salesBar}>
                        <Bar height={295} title="文章趋势" data={articleGroupData} />
                      </div>
                    </Col>
                    <Col xl={8} lg={12} md={12} sm={24} xs={24}>
                      <div className={styles.salesRank}>
                        <h4 className={styles.rankingTitle}>文章（按阅读排名）</h4>
                        <ul className={styles.rankingList}>
                          {articleRankData.map((item, i) => (
                            <li key={item.title}>
                              <span className={i < 3 ? styles.active : ''}>{i + 1}</span>
                              <span><a href={item.src} target="_bank">{item.title.substring(0, 20) }..</a></span>
                              <span>{numeral(item.view).format('0,0')}</span>
                            </li>
                          ))}
                        </ul>
                      </div>
                    </Col>
                  </Row>
                </TabPane>
                <TabPane tab="百家号采集" key="views">
                  <Row>
                    <Col xl={16} lg={12} md={12} sm={24} xs={24}>
                      <div className={styles.salesBar}>
                        <Bar height={292} title="百家号趋势" data={baiJiaGroupData} />
                      </div>
                    </Col>
                    <Col xl={8} lg={12} md={12} sm={24} xs={24}>
                      <div className={styles.salesRank}>
                        <h4 className={styles.rankingTitle}>百家号（按粉丝排名）</h4>
                        <ul className={styles.rankingList}>
                          {baiJiaRankData.map((item, i) => (
                            <li key={item.title}>
                              <span className={i < 3 ? styles.active : ''}>{i + 1}</span>
                              <span><a href={item.home_url} target="_bank">{item.name}</a></span>
                              <span>{numeral(item.fans).format('0,0')}</span>
                            </li>
                          ))}
                        </ul>
                      </div>
                    </Col>
                  </Row>
                </TabPane>
              </Tabs>
            </div>
          </Card>
          <Row gutter={24}>
            <Col xl={12} lg={24} md={24} sm={24} xs={24}>
              <Card
                loading={loading}
                className={styles.salesCard}
                bordered={false}
                title="话题热点"
                bodyStyle={{ padding: 24 }}
                style={{ marginTop: 24, minHeight: 509 }}
                extra={
                  <div className={styles.salesCardExtra}>
                    <div className={styles.salesTypeRadio}>
                      <Radio.Group value={hotType} onChange={this.handleChangeHot}>
                        <Radio.Button value="实时热点">实时热点</Radio.Button>
                        <Radio.Button value="今日热点">今日热点</Radio.Button>
                        <Radio.Button value="七日热点">七日热点</Radio.Button>
                      </Radio.Group>
                    </div>
                  </div>
                }
              >
                <Table
                  rowKey={record => record.rank}
                  size="small"
                  columns={columns}
                  dataSource={hotData}
                />
              </Card>
            </Col>
            <Col xl={12} lg={24} md={24} sm={24} xs={24}>
              <Card
                loading={loading}
                className={styles.salesCard}
                bordered={false}
                title="百家号领域"
                bodyStyle={{ padding: 24 }}
                style={{ marginTop: 24, minHeight: 625 }}
              >
                <h4 style={{ marginTop: 8, marginBottom: 32 }}>Top 12</h4>
                <Pie
                  hasLegend
                  subTitle="总量(所有)"
                  total={ratioTotal}
                  data={ratioData}
                  valueFormat={value => value}
                  height={400}
                  lineWidth={6}
                />
              </Card>
            </Col>
          </Row>
        </Fragment>
      </Spin>
    );
  }
}
